package com.hkts.naturalgas.performance.controller;

import cn.hutool.core.date.DateTime;
import com.hkts.naturalgas.performance.entity.HkPictureInfo;
import com.hkts.naturalgas.performance.service.IHkPictureInfoService;
import com.hkts.naturalgas.performance.service.serviceimpl.HkPictureInfoServiceImpl;
import com.hkts.naturalgas.utils.*;
import com.qiniu.common.QiniuException;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping("/performance/uploadController")
public class HkUploadPictureController {
    @Autowired
    private QiniuUtil qiniuUtil;
    @Autowired
    private IHkPictureInfoService HkPictureInfoServiceImpl;


    @ResponseBody
    @PostMapping("/uploadPicture")
    public Result<Object> uploadPicture(@ApiParam(name="file",value = "照片",required=true) MultipartFile file) {
        String oldName = file.getOriginalFilename();
        //1.2使用IDUtils工具类生成新的文件名，新文件名 = newName + 文件后缀

        String newName = IDUtils.genImageName();
        assert oldName != null;
        newName = newName + oldName.substring(oldName.lastIndexOf("."));
        //1.3生成文件在服务器端存储的子目录
        String filePath = new DateTime().toString("/yyyyMMdd/");

        //2、把图片上传到图片服务器
        //2.1获取上传的io流
        InputStream input = null;
        try {
            input = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String key = IDUtils.genImageName();
        String iamgePath= qiniuUtil.qiniuInputStreamUpload(input, key);
        /*
        * 保存图片信息
        * */
      HkPictureInfo info=new HkPictureInfo();
        info.setId(IDUtils.genImageName());
        info.setPictureKey(key);
        info.setPictureUrl(iamgePath);
        HkPictureInfoServiceImpl.save(info);
        return ResultUtil.data(iamgePath);
    }

    /*
    * 删除图片
    * */
    @ResponseBody
    @PostMapping("/deleteImage")
    public Result<Object> deletePicture(String imageUrl) throws QiniuException {
        HkPictureInfo info=new HkPictureInfo();
        info.setPictureUrl(imageUrl);
        List<HkPictureInfo> hkPictureInfos = HkPictureInfoServiceImpl.selectList(info);
        if (hkPictureInfos.size()>0){
           qiniuUtil.deleteImage(hkPictureInfos.get(0).getPictureKey());
        }
        HkPictureInfoServiceImpl.removeById(hkPictureInfos.get(0).getId());
        return ResultUtil.data("删除成功");
    }


}
